package com.ctgu.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.server.dao.constant.CacheKey;
import com.ctgu.server.dao.constant.ResultEnum;
import com.ctgu.server.dao.dto.UserDto;
import com.ctgu.server.dao.entity.Role;
import com.ctgu.server.dao.entity.User;
import com.ctgu.server.dao.vo.Result;
import com.ctgu.server.dao.vo.TokenVo;
import com.ctgu.server.dao.vo.UserVo;
import com.ctgu.server.mapper.UserMapper;
import com.ctgu.server.service.RoleService;
import com.ctgu.server.service.UserService;
import com.ctgu.server.utils.JWTUtil;
import com.ctgu.server.utils.ResultUtil;
import com.ctgu.server.utils.oss.OssClientUtils;
import com.github.dozermapper.core.Mapper;
import net.oschina.j2cache.CacheChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ctgu
 * @since 2023-05-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private Mapper mapper;
    @Autowired
    private CacheChannel cacheChannel;

    @Autowired
    private RoleService roleService;

    @Override
    public Result UserLogin( Map<String, Object> access_map) {
        String access_token=access_map.get("openid").toString();
//        String access_token="dasdasdsadas";
        //1.查询该用户是否存在

        User user=selectUser(access_token);
        if(user==null){
            //1.1注册新用户
            user=new User();
            user.setId(access_token);
            user.setUserName(access_token);
//            user.setUserStatus(1);  //默认为在线状态
            user.setRoleId("1"); //默认为游客
            //1.2在数据库注册用户
            this.save(user);
        }


        String token=JWTUtil.generateToken(access_map);
        //4.设置用户登录证明
        cacheChannel.set(CacheKey.Access_key,access_token,token);
        //5.返回数据给前端
        TokenVo tokenVo=new TokenVo(mapper.map(user, UserVo.class),token);

        return ResultUtil.success(tokenVo);
    }

//    @Override
//    public Result userRegister(RegisterDto registerDto) {
//        //1.查询该用户是否存在
//        User user=selectUser(registerDto.getUserName());
//        if(user!=null){
//            return ResultUtil.error(ResultEnum.REGISTER_FAILED_EXIT);
//        }
//        //2,创建新的用户
//        user= mapper.map(registerDto, User.class);
//        user.setUserStatus(1);
//
//        this.save(user);
//
//        return ResultUtil.success();
//    }

    @Override
    public Result getUserInfo(String id) {
        //1.鉴权
//        Claims claims= JWTUtil.parseToken(loginDto.getToken());
//        if(!loginDto.getUserName().equals( claims.get("userName"))){
//            return ResultUtil.error("非法访问！");
//        }
//        CacheObject cacheObject = cacheChannel.get(CacheKey.UUID_KEY,.getUserName());
//        if(cacheObject==null||!loginDto.getUuid().equals(cacheObject.getValue().toString())){
//            return ResultUtil.error("非法访问！");
//        };
        //2.查询用户
        User user=selectUser(id);
        if(user==null){
            return ResultUtil.error(ResultEnum.LOGIN_FAILED_NOT_EXITES);
        }
        //3.查询用户角色信息
        Role role= roleService.getById(user.getRoleId());

        //3.处理参数
        UserVo userVo= mapper.map(user, UserVo.class);
        userVo.setIdentify(role.getRoleName());
        return ResultUtil.success(userVo);
    }

    @Override
    public Result updateByUserId(UserDto uservo) {
        User user=selectUser(uservo.getId());
        if(user==null){
            return ResultUtil.error(ResultEnum.LOGIN_FAILED_NOT_EXITES);
        }
        LambdaUpdateWrapper<User> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getId,user.getId());
        user=mapper.map(uservo,User.class);

        boolean flag= this.update(user,lambdaUpdateWrapper);
        if(!flag){
            return ResultUtil.error("更新失败");
        }
        return ResultUtil.success("更新成功");
    }

    @Override
    public Result uploadUserAvatar(String id, MultipartFile multipartFile) {
        //1.查询用户是否存在
        User user= selectUser(id);
        if(user==null){
            return ResultUtil.error("请求用户不存在!");
        }
        //2.拼接文件名
        String url= OssClientUtils.upload(multipartFile);
        if(url==null){
            return ResultUtil.error("文件上传失败");
        }
        //3.更新用户头像
        user.setUserAvatar(url);
        LambdaUpdateWrapper<User> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getId,user.getId());

        this.update(user,lambdaUpdateWrapper);
       //4.返回用户数据
        return ResultUtil.success("上传成功",url);
    }

//    @Override
//    public Result updateUserByUName(User user) {
//        this.save(user);
//        return null;
//    }

    public User selectUser(String openid){
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getId,openid);
        return this.getOne(lambdaQueryWrapper,false);
    }
    //判断当前用户列表有多少在
    public int countInUserList (List<String> userList){
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(User::getId,userList);
        return this.count(lambdaQueryWrapper);
    }
}
